package seq;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class CertNOGeneratorV1 {
    private static final int tc = 2000;
    private boolean init = false;
    private ConcurrentHashMap<Long, AtomicInteger> hashMap = new ConcurrentHashMap<>();
    private static ExecutorService executorService = Executors.newFixedThreadPool(tc);

    private Thread clearThread;

    public static void main(String[] args) throws FileNotFoundException, InterruptedException {

        CertNOGeneratorV1 certNOGenerator = new CertNOGeneratorV1();


        ByteArrayOutputStream[] ss = new ByteArrayOutputStream[tc];
        CountDownLatch downLatch = new CountDownLatch(tc);

        for (int i = 0; i < tc; i++) {
            ByteArrayOutputStream si = new ByteArrayOutputStream(40000);
            ss[i] = si;
        }

        long end = System.currentTimeMillis() + 60000;
        for (int i = 0; i < tc; i++) {
            PrintWriter out = new PrintWriter(ss[i]);
            executorService.submit(() -> {
                while (System.currentTimeMillis() <= end) {
                    out.println(certNOGenerator.nextNO());
                }
                out.flush();
                downLatch.countDown();
            });
        }

        downLatch.await();
        System.out.println(System.currentTimeMillis() - end);
        executorService.shutdown();
        System.out.println(certNOGenerator.hashMap.size());

        PrintStream printStream = new PrintStream(new FileOutputStream("D:/nos.txt"));
        for (int i = 0; i < tc; i++) {
            printStream.print(ss[i].toString());
        }
        printStream.close();
    }


    public CertNOGeneratorV1() {
        init();
    }

    public synchronized void init() {
        if (!init) {
            clearThread = new Thread(this::clearKeys);
            clearThread.setDaemon(true);
            clearThread.start();
            init = true;
        }

    }

    public synchronized void destroy() {
        clearThread = null;
    }

    public String nextNO() {
        init();

        long key = System.currentTimeMillis();
        AtomicInteger atomicIntNo = hashMap.computeIfAbsent(key, k -> new AtomicInteger(0));
        int no = atomicIntNo.get();
        boolean less = no < 99;
        if (less) {
            no = atomicIntNo.incrementAndGet();
        }
        if (!less || no > 99) {
            //编号不足时，睡眠到下一毫秒秒生成
            sleepToNextMill();
            return nextNO();
        }
        String seq = String.format(key + "_%02d", no);
        return seq;
    }

    private void sleepToNextMill() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException ignore) {

        }
    }

    private void clearKeys() {
        while (true) {
            try {
                Thread.sleep(5000);
                long millis = System.currentTimeMillis();
                Iterator<Map.Entry<Long, AtomicInteger>> iterator = hashMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Long, AtomicInteger> next = iterator.next();
                    Long key = next.getKey();
                    if (key < millis - 5000) {
                        System.out.println("删除" + key);
                        iterator.remove();
                    }
                }
            } catch (Throwable ignore) {

            }
        }
    }
}
